﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
using System;


namespace GameName1
{
    /// <summary>
    /// A game component.
    /// Has an associated rectangle.
    /// Accepts touch and click inside the rectangle.
    /// Has a state of IsTouching and IsClicked.
    /// </summary>
    public class Clickable: GameComponent
    {

        #region Fields
        readonly Rectangle rectangle;
        bool wasTouching;
        bool isTouching;
        SoundEffect soundEffect;
        public event EventHandler OnClick;

        #region Protected accessors
        public bool IsTouching { get { return isTouching; } }
        public bool IsClicked { get { return (wasTouching == true) && (isTouching == false); } }

        protected Rectangle Rectangle { get { return rectangle; } }
       // protected new Game1 Game { get { return (Game1)base.Game; } }
        #endregion
        #endregion

        #region Initialization
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="game">The Game oject</param>
        /// <param name="targetRectangle">Position of the component on the screen</param>
        public Clickable( Game game, Rectangle targetRectangle)
            :base(game, new Vector2(targetRectangle.X, targetRectangle.Y))
        {
            rectangle = targetRectangle;
            //song = game.Content.Load<Song>("woosh");
            soundEffect = game.Content.Load<SoundEffect>("woosh2");

        }
        #endregion

        #region Input handling
        /// <summary>
        /// Handles Input
        /// </summary>
        public override void HandleInput(TouchCollection touches)
        {
            wasTouching = isTouching;
            isTouching = false;

           // TouchCollection touches = TouchPanel.GetState();

            if (touches.Count > 0)
            {
                var touch = touches[0];
                var position = touch.Position;


                Rectangle touchRect = new Rectangle((int)touch.Position.X - 5, (int)touch.Position.Y - 5,
                    10, 10);

                if (rectangle.Intersects(touchRect))
                    isTouching = true;
            }

            if (!wasTouching && isTouching)
            {
                soundEffect.Play();
            }

            if (wasTouching && !isTouching)
            {
                if(OnClick != null)
                {
                    this.OnClick(this, null);
                }
            }
        }

        #endregion
    }
}
